<?php

/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2019/3/27
 * Time: 09:34
 */
namespace app\common\lib;

use think\Config;

class Redis
{
    public $redis = '';

    private static $_instance;

    public static function getInstance(){
        if (empty(self::$_instance)){
            self::$_instance = new self();
        }
        return self::$_instance;
    }
   private  function __construct()
    {
        $config = Config::get('cache.redis');
        try{
            $this->redis = new \Redis();
            $this->redis->connect($config['host'],6379,5);
            $this->redis->auth($config['password']);
        }catch (\Exception $exception){
            //todo 服务通知，redis服务挂掉，短信，邮件
            echo $exception->getMessage();
        }
    }
    /**
     * 设置缓存
     * @param $num 数据库编号
     * @param $key 键名
     * @param $value
     * @param int $time
     * @return bool|string
     */
    public function set($num=1,$key,$value, $time=0){
        if (!$key){
            return '';
        }
        if (is_array($value)){
            $value = json_encode($value);
        }
        $this->redis->select($num);
        if ($time == 0){
           return  $this->redis->set($key,$value);
        }else{
            return $this->redis->setex($key,$time,$value);
        }
    }
    /**
     * 获取缓存
     * @param $num
     * @param $key
     * @return bool|string
     */
    public function get($num=1,$key){
        $this->redis->select($num);//选着数据库
        $str = $this->redis->get($key);
        if (!$str){
            return '';
        }
        return json_decode($str,true);
    }

    /**
     * 删除redis缓存
     * @param int $num
     * @param $key
     * @return int
     */
    public function del($num=1,$key){
        $this->redis->select($num);//选着数据库
        return $this->redis->del($key);
    }

    /**
     * 批量获取指定前缀的key值
     * @param int $num
     * @param $key
     * @return array|bool|null
     */
    public function getKeys($num=1,$key){
        $this->redis->setOption( $this->redis::OPT_SCAN, $this->redis::SCAN_RETRY);
        $this->redis->select($num);//选着数据库
        $iterator = null;
        while ($keys = $this->redis->scan($iterator, $key)){
            return $keys;
        };
        return null;
    }

    /**
     * 批量删除key
     * @param int $num
     * @param $key
     * @return bool
     */
    public function delKeys($num=1,$key){
        $this->redis->setOption( $this->redis::OPT_SCAN, $this->redis::SCAN_RETRY);
        $this->redis->select($num);//选着数据库
        $iterator = null;
        while ($keys = $this->redis->scan($iterator, $key)){
            foreach ($keys as $item){
              $str = $this->redis->del($item);
              if ($str != 1){
                  return false;
              }
            }
        };
        return true;
    }

}